#include "LogManager.h"

namespace logging {

LogManager *LogManager::_instance = NULL;

LogManager::LogManager() {
	//Config
	_output = new LogOutput();
	_output->start();
}

LogManager::~LogManager() {
	delete _output;
}

LogManager *LogManager::getInstance() {
	if ( !_instance ) {
		_instance = new LogManager();
	}
	return _instance;
}

/**
 * Does a lookup to see if a log namespace already exists
 * if it does it returns this one or instaniates a new one
 */
Log *LogManager::getLog(char* ns) {
	LogManager *mng = LogManager::getInstance();
	return mng->createOrReturn(ns);
}

Log *LogManager::createOrReturn(char* ns) {
	Log *log = NULL;

	_lMutex.lock();
	LogMap::const_iterator it = _logs.find(ns);
	if ( it == _logs.end() ) {
		//create new log and store
		//log = new Log(_output, ns, Config::getValue("logging.level.default", WARN));
		log = new Log(_output, ns);
		_logs[ns] = log;
	} else {
		log = (*it).second;
	}
	_lMutex.unlock();
	return log;
}

LogMapIterator::LogMapIterator(LogMap *map) 
	: _map(map) {
	_current = _map->begin();
}

bool LogMapIterator::hasNext() const {
	return (_current != _map->end());
}

Log* LogMapIterator::next() {
	Log *log = (*_current).second;
	_current++;
	return log;
}

}

